package com.study.ming.websocket;

import com.study.ming.feign.ProductService;
import com.study.ming.feign.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class HelloController {

    @Resource //注入接口，可进行调用，类似于service中注入xxxMapper
    ProductService productService;
    @Resource //注入接口，可进行调用，类似于service中注入xxxMapper
    WeatherService weatherService;
    @Autowired
    private DiscoveryClient discoveryClient;

    private final RestTemplate restTemplate;
    @Autowired
    public HelloController(RestTemplate restTemplate) {this.restTemplate = restTemplate;}

    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    public String echo(@PathVariable String str) {
        List<String> services = discoveryClient.getServices();
        System.out.println(services);
        List<ServiceInstance> nacosprovider = discoveryClient.getInstances("nacosprovider");
        ServiceInstance instance = nacosprovider.get(0);
        System.out.println(instance.getInstanceId() + instance.getServiceId()+instance.getHost()+instance.getPort()+instance.getUri());

        //这三个地方都报错了 No instances available for 127.0.0.1 192.168. nacosprovider
//        ResponseEntity<String> entity2 = restTemplate.getForEntity("http://127.0.0.1:8081/echo2/" + str, String.class);
//        System.out.println(entity2);
//        ResponseEntity<String> entity3 = restTemplate.getForEntity(instance.getUri()+"/echo2/" + str, String.class);
//        System.out.println(entity3);
//        ResponseEntity<String> entity = restTemplate.getForEntity("http://nacosprovider/echo2/" + str, String.class);
//        return entity.getBody();
        return productService.echo();
    }
    @RequestMapping(value = "/getWeather", method = RequestMethod.GET)
    public String getWeather(@RequestParam(name="id", value = "id", required = false, defaultValue = "1") Integer id) {
        return weatherService.getByCity(id);
    }
    @RequestMapping(value = "/echo2/{str}", method = RequestMethod.GET)
    public String echo2(@PathVariable String str) {
        return str+"this is from gateway echo2";
    }
}
